<template>
	<view class="personal-container">
		<!-- 登录授权弹窗 -->
		<view v-if="showAuthModal" class="auth-modal-overlay" @tap="closeAuthModal">
			<view class="auth-modal" @tap.stop>
				<view class="auth-modal-header">
					<image class="auth-modal-logo" src="/static/other/logo2019.jpg" mode="aspectFit"></image>
					<view class="auth-modal-title">欢迎使用心域SAAS系统</view>
					<view class="auth-modal-subtitle">为了给您提供更好的服务，需要获取您的微信信息</view>
				</view>

				<view class="auth-modal-content">
					<view class="auth-benefits">
						<view class="benefit-item">
							<text class="benefit-icon">⚡欢迎加入</text>
							<text class="benefit-text">加入我们,一起成长!</text>
						</view>
					</view>
				</view>

				<view class="auth-modal-actions">
					<!-- 完整授权按钮 -->
					<button class="auth-btn auth-btn-primary" open-type="getPhoneNumber"
						@getphonenumber="handleCompleteAuth" :loading="isLogging">
						{{ isLogging ? '登录中...' : '完整授权登录' }}
					</button>

					<button class="auth-btn auth-btn-text" @tap="closeAuthModal">
						暂不登录
					</button>
				</view>
			</view>
		</view>

		<custom-navbar title="个人中心"></custom-navbar>
		<!-- 顶部导航 -->
		<!-- 	<view class="nav-bar">
			<view class="nav-icon" @click="navigateToMessage">
				<image src="/static/agency/phone.png" mode="aspectFit"></image>
			</view>
			<view class="nav-icon" @click="navigateToSetting">
				<image src="/static/agency/share.png" mode="aspectFit"></image>
			</view>
		</view> -->
		<view class="bg-p">
			<view class="">
				<image src="/static/other/bg-top.png" mode="aspectFill" class="bg-image"></image>
			</view>
			<view class="fixed-position">
				<!-- 用户信息区域 start-->
				<view class="user-info">
					<view class="avatar-container">
						<image class="avatar" :src="'https://iepsy.oss-cn-beijing.aliyuncs.com/'+userInfo.avatar"
							mode="aspectFit"></image>
					</view>
					<view class="user-details">
						<view class="username">{{userInfo.nickname}}</view>
						<view v-if="isLoggedIn" class="edit-btn" @click="editProfile">
							<image class="edit-btn-img" src="/static/pecenter/edit.png" mode="aspectFill"></image>
							编辑
						</view>
						<view v-else class="login-btn" @click="goToLogin">去登录</view>
					</view>
				</view>
				<!-- 用户信息区域 end-->
				<!-- 订单区域 start-->
				<view class="order-section">
					<view class="order-tabs">
						<!-- <view class="order-tab" @click="navigateToOrder('all')">
							<image src="/static/pecenter/all-orders.png" mode="aspectFit"></image>
							<text>全部订单</text>
						</view>
						<view class="order-tab" @click="navigateToOrder('valid')">
							<image src="/static/pecenter/valid-order.png" mode="aspectFit"></image>
							<text>有效订单</text>
						</view>
						<view class="order-tab" @click="navigateToOrder('unpaid')">
							<image src="/static/pecenter/pprder.png" mode="aspectFit"></image>
							<text>待支付订单</text>
						</view>
						<view class="order-tab" @click="navigateToOrder('refund')">
							<image src="/static/pecenter/re-order.png" mode="aspectFit"></image>
							<text>退款订单</text>
						</view> -->
					</view>
				</view>
				<!-- 订单区域 end-->
				<!-- 功能列表区域 start-->
				<view class="function-list">
					<!-- <view class="function-item" @click="navigateToConsultantBooking">
					<view class="function-icon">
						<image src="/static/pecenter/book-counselor.png" mode="aspectFit"></image>
					</view>
					<text class="function-text">预约咨询师</text>
					<view class="arrow-icon">
						<image src="/static/pecenter/return.png" mode="aspectFit"></image>
					</view>
				</view> -->

					<!-- <view class="function-item" @click="navigateToRoomBooking">
					<view class="function-icon">
						<image src="/static/pecenter/cons-room.png" mode="aspectFit"></image>
					</view>
					<text class="function-text">预约咨询室</text>
					<view class="arrow-icon">
						<image src="/static/pecenter/return.png" mode="aspectFit"></image>
					</view>
				</view> -->

					<!-- <view class="function-item" @click="navigateToActivityBooking">
					<view class="function-icon">
						<image src="/static/pecenter/event-reservation.png" mode="aspectFit"></image>
					</view>
					<text class="function-text">预约活动</text>
					<view class="arrow-icon">
						<image src="/static/pecenter/return.png" mode="aspectFit"></image>
					</view>
				</view> -->

					<!-- 	<view class="function-item" @click="navigateToMyCourses">
					<view class="function-icon">
						<image src="/static/pecenter/my-courses.png" mode="aspectFit"></image>
					</view>
					<text class="function-text">我的课程</text>
					<view class="arrow-icon">
						<image src="/static/pecenter/return.png" mode="aspectFit"></image>
					</view>
				</view> -->

					<!-- 	<view class="function-item" @click="navigateToMyEvaluations">
					<view class="function-icon">
						<image src="/static/pecenter/my-evaluation.png" mode="aspectFit"></image>
					</view>
					<text class="function-text">我的测评</text>
					<view class="arrow-icon">
						<image src="/static/pecenter/return.png" mode="aspectFit"></image>
					</view>
				</view> -->

					<!-- <view class="function-item" @click="navigateToMyProducts">
					<view class="function-icon">
						<image src="/static/pecenter/my-product.png" mode="aspectFit"></image>
					</view>
					<text class="function-text">我的产品</text>
					<view class="arrow-icon">
						<image src="/static/pecenter/return.png" mode="aspectFit"></image>
					</view>
				</view> -->

					<!-- <view class="function-item" @click="navigateToProfile">
					<view class="function-icon">
						<image src="/static/pecenter/archive.png" mode="aspectFit"></image>
					</view>
					<text class="function-text">个人资料</text>
					<view class="arrow-icon">
						<image src="/static/pecenter/return.png" mode="aspectFit"></image>
					</view>
				</view> -->

					<view class="function-item" @click="navigateToJoin">
						<view class="function-icon">
							<image src="/static/pecenter/franchise.png" mode="aspectFit"></image>
						</view>
						<text class="function-text">加盟入驻</text>
						<view class="arrow-icon">
							<image src="/static/pecenter/return.png" mode="aspectFit"></image>
						</view>
					</view>

					<!-- 	<view class="function-item" @click="navigateToCustomerService">
					<view class="function-icon">
						<image src="/static/pecenter/contact-customer.png" mode="aspectFit"></image>
					</view>
					<text class="function-text">联系客服</text>
					<view class="arrow-icon">
						<image src="/static/pecenter/return.png" mode="aspectFit"></image>
					</view>
				</view> -->

					<view class="function-item" @click="logout">
						<view class="function-icon">
							<image src="/static/pecenter/log-out.png" mode="aspectFit"></image>
						</view>
						<text class="function-text">退出登录</text>
						<view class="arrow-icon">
							<image src="/static/pecenter/return.png" mode="aspectFit"></image>
						</view>
					</view>
				</view>
				<!-- 功能列表区域 end-->
			</view>


		</view>






	</view>
</template>

<script>
	import {
		getInsFormSub
	} from '../../api/api.js'
	import enhancedAuthManager from '../../utils/auth.js'
	import customNavbar from '../../components/custom-navbar/custom-navbar.vue';

	export default {
		data() {
			return {
				userInfo: {
					id: 0,
					phone: '',
					aid: 0,
					openid: '',
					unionid: '',
					nickname: '匿名用户',
					avatar: '/static/tab/avatar.png'
				},
				isLoggedIn: false,
				// 登录相关状态
				showAuthModal: false,
				isLogging: false
			}
		},

		onShow() {
			// 每次显示页面时检查登录状态
			this.checkLoginStatus()

			// 如果未登录，显示授权弹窗
			if (!this.isLoggedIn) {
				setTimeout(() => {
					this.showAuthModal = true;
				}, 500);
			}
		},

		onLoad() {
			// 页面加载时检查登录状态
			this.checkLoginStatus()
		},
		methods: {
			/**
			 * 检查登录状态
			 */
			checkLoginStatus() {
				// console.log('🔍 个人中心检查登录状态...')

				if (enhancedAuthManager.isLoggedIn()) {
					const userInfo = enhancedAuthManager.getUserInfo()
					if (userInfo) {
						this.isLoggedIn = true
						this.userInfo = {
							nickname: userInfo.nickname || '微信用户',
							avatar: userInfo.avatar || '/static/tab/avatar.png',
							phone: userInfo.phone,
							id: userInfo.id,
							openid: userInfo.openid,
							unionid: userInfo.unionid,
							aid: userInfo.aid,
						}
						// console.log('✅ 用户已登录:', this.userInfo.nickname)
					} else {
						this.setAnonymousUser()
					}
				} else {
					this.setAnonymousUser()
				}
			},

			/**
			 * 设置匿名用户状态
			 */
			setAnonymousUser() {
				this.isLoggedIn = false
				this.userInfo = {
					nickname: '匿名用户',
					avatar: '/static/tab/avatar.png'
				}
				// console.log('👤 设置为匿名用户')
			},

			/**
			 * 跳转到登录页面
			 */
			goToLogin() {
				// console.log('🔗 跳转到首页进行登录')
				uni.switchTab({
					url: '/pages/home/home'
				})
			},

			// 导航到消息页面（暂未实现，使用提示代替）
			navigateToMessage() {
				uni.showToast({
					title: '消息功能开发中',
					icon: 'none'
				})
			},

			// 导航到设置页面（暂未实现，使用提示代替）
			navigateToSetting() {
				uni.showToast({
					title: '设置功能开发中',
					icon: 'none'
				})
			},

			// 编辑个人资料（暂未实现，使用提示代替）
			editProfile() {
				uni.showToast({
					title: '编辑资料功能开发中',
					icon: 'none'
				})
			},

			// 导航到订单页面（暂未实现，使用提示代替）
			navigateToOrder(type) {
				uni.showToast({
					title: '订单功能开发中',
					icon: 'none'
				})
			},

			// 导航到预约咨询师页面
			navigateToConsultantBooking() {
				uni.switchTab({
					url: '/pages/consult/consult'
				})
			},

			// 导航到预约咨询室页面
			navigateToRoomBooking() {
				uni.navigateTo({
					url: '/pages/conroomlist/conroomlist'
				})
			},

			// 导航到预约活动页面
			navigateToActivityBooking() {
				uni.switchTab({
					url: '/pages/activity/activity'
				})
			},

			// 导航到我的课程页面
			navigateToMyCourses() {
				uni.switchTab({
					url: '/pages/course/course'
				})
			},

			// 导航到我的测评页面（暂未实现，使用提示代替）
			navigateToMyEvaluations() {
				uni.showToast({
					title: '测评功能开发中',
					icon: 'none'
				})
			},

			// 导航到我的产品页面（暂未实现，使用提示代替）
			navigateToMyProducts() {
				uni.showToast({
					title: '产品功能开发中',
					icon: 'none'
				})
			},

			// 导航到个人资料页面（暂未实现，使用提示代替）
			navigateToProfile() {
				uni.showToast({
					title: '个人资料功能开发中',
					icon: 'none'
				})
			},

			// 导航到加盟入驻页面
			navigateToJoin() {
				uni.navigateTo({
					url: '/pages/personal/franchise'
				})
			},
			// 导航到招聘申请表
			navigateToApply() {
				uni.navigateTo({
					url: '/pages/recruitment/recruitment'
				})
			},

			// 导航到联系客服页面（暂未实现，使用提示代替）
			navigateToCustomerService() {
				uni.showToast({
					title: '客服功能开发中',
					icon: 'none'
				})
			},


			/**
			 * 显示授权弹窗
			 */
			showAuthModalDialog() {
				this.showAuthModal = true;
			},

			/**
			 * 关闭授权弹窗
			 */
			closeAuthModal() {
				this.showAuthModal = false;
			},

			/**
			 * 处理完整授权登录
			 */
			async handleCompleteAuth(e) {
				if (e.detail.errMsg !== 'getPhoneNumber:ok') {
					uni.showToast({
						title: '需要手机号授权才能使用完整功能',
						icon: 'none',
						duration: 3000
					});
					return;
				}

				this.isLogging = true;

				try {
					// 获取微信登录code
					const code = await new Promise((resolve, reject) => {
						uni.login({
							provider: 'weixin',
							success: (loginRes) => {
								resolve(loginRes.code)
							},
							fail: (error) => {
								reject(error)
							}
						})
					});

					// 准备基础用户信息
					const userInfo = {
						nickName: '微信用户',
						avatarUrl: '/static/logo.png',
						gender: 0,
						country: '',
						province: '',
						city: '',
						language: 'zh_CN'
					};

					// 准备登录数据
					const loginData = {
						code: code,
						encryptedData: e.detail.encryptedData,
						iv: e.detail.iv,
						cloudID: e.detail.cloudID,
						userInfo: userInfo,
						timestamp: Date.now(),
						platform: 'wechat-miniprogram'
					}

					// 调用登录接口
					const result = await enhancedAuthManager.wxLogin(loginData);

					if (result.success) {
						// 保存登录信息
						enhancedAuthManager.saveLoginInfo(result.token, result.userInfo);

						this.userInfo = result.userInfo;
						this.isLoggedIn = true;
						this.showAuthModal = false;

						uni.showToast({
							title: '登录成功',
							icon: 'success',
							duration: 2000
						});
					} else {
						throw new Error(result.error || '登录失败')
					}
				} catch (error) {
					console.error('❌ 登录失败:', error);
					uni.showToast({
						title: error.message || '登录失败，请重试',
						icon: 'none',
						duration: 3000
					});
				} finally {
					this.isLogging = false;
				}
			},

			// 退出登录
			async logout() {
				if (!this.isLoggedIn) {
					uni.showToast({
						title: '您还未登录',
						icon: 'none'
					})
					return
				}

				uni.showModal({
					title: '退出登录',
					content: '确定要退出登录吗？',
					confirmText: '确定',
					cancelText: '取消',
					success: async (res) => {
						if (res.confirm) {
							try {
								// console.log('🚪 用户确认退出登录')
								const result = await enhancedAuthManager.performLogout()
								if (result.success) {
									// 更新页面状态
									this.setAnonymousUser()
									// console.log('✅ 退出登录成功，页面状态已更新')

									// 返回首页
									setTimeout(() => {
										uni.switchTab({
											url: '/pages/home/home'
										})
									}, 1000)
								}
							} catch (error) {
								// console.error('❌ 退出登录失败:', error)
								uni.showToast({
									title: '退出失败，请重试',
									icon: 'none'
								})
							}
						}
					}
				})
			}
		}
	}
</script>

<style>
	/* 容器样式 */
	.personal-container {
		width: 100%;
		min-height: 100vh;
		background-color: #f5f5f5;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
	}

	/* 顶部导航样式 */
	.nav-bar {
		display: flex;
		justify-content: flex-end;
		padding: 20rpx 30rpx;
		background-color: #fff;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.nav-icon {
		width: 60rpx;
		height: 60rpx;
		margin-left: 40rpx;
	}

	.nav-icon image {
		width: 100%;
		height: 100%;
	}

	.bg-p {
		position: relative;
		height: 450rpx;
		margin-top: 190rpx;
		background-size: cover;
	}

	.bg-image {
		position: absolute;
		width: 100%;
		height: 100%;
		/* z-index: -1; */
	}

	.fixed-position {
		position: absolute;
	}

	/* 用户信息区域样式 */
	.user-info {
		display: flex;
		align-items: center;
		padding: 30rpx;
		/* background-color: #fff; */
		border-bottom: 1rpx solid #eee;

	}

	.avatar-container {
		width: 140rpx;
		height: 140rpx;
		border-radius: 50%;
		overflow: hidden;
		background-color: #f0f0f0;
		border: 4rpx solid #fff;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
	}

	.avatar {
		width: 100%;
		height: 100%;
	}

	.user-details {
		margin-left: 30rpx;
		/* flex: 1; */
		/* display: flex; */
		/* justify-content: space-between; */
		/* align-items: center; */
	}

	.username {
		font-size: 40rpx;
		font-weight: 600;
		color: #333;
		padding-right: 30rpx;
		padding-bottom: 15rpx;
	}

	.edit-btn {
		width: 80rpx;
		font-size: 25rpx;
		color: #999;
		padding: 10rpx 20rpx;
		border: 1rpx solid #ddd;
		border-radius: 20rpx;
		line-height: 27rpx;
	}

	.edit-btn-img {
		width: 23rpx;
		height: 23rpx;
	}

	.login-btn {
		width: 85rpx;
		font-size: 28rpx;
		color: #fff;
		background: linear-gradient(135deg, #3B82F6 0%, #1D4ED8 100%);
		padding: 10rpx 20rpx;
		border-radius: 20rpx;
		border: none;
	}

	.login-btn:active {
		opacity: 0.8;
	}

	/* 订单区域样式 */
	.order-section {
		margin-top: 20rpx;
		/* background-color: #fff; */
		padding: 30rpx 0;
	}

	.order-tabs {
		width: 750rpx;
		display: flex;
		justify-content: space-around;
	}

	.order-tab {
		width: 22.2%;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.order-tab image {
		width: 70rpx;
		height: 70rpx;
		margin-bottom: 10rpx;
	}

	.order-tab text {
		font-size: 28rpx;
		color: #333;
	}

	/* 功能列表样式 */
	.function-list {
		margin-top: 20rpx;
		background-color: #fff;
		width: 700rpx;
		margin: 5rpx auto;
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
	}

	.function-item {
		display: flex;
		align-items: center;
		padding: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
		tap-highlight-color: transparent;
		user-select: none;
	}

	.function-item:active {
		background-color: #f8f8f8;
	}

	.function-icon {
		width: 25rpx;
		height: 25rpx;
	}

	.function-icon image {
		width: 100%;
		height: 100%;
	}

	.function-text {
		flex: 1;
		margin-left: 30rpx;
		margin-top: 17rpx;
		font-size: 30rpx;
		color: #333;
	}

	.arrow-icon {
		width: 30rpx;
		height: 30rpx;
	}

	.arrow-icon image {
		width: 100%;
		height: 100%;
	}

	/* 登录授权弹窗样式 */
	.auth-modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.6);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9999;
		padding: 40rpx;
	}

	.auth-modal {
		background-color: white;
		border-radius: 32rpx;
		padding: 60rpx 40rpx 40rpx;
		width: 100%;
		max-width: 600rpx;
		box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.3);
	}

	.auth-modal-header {
		text-align: center;
		margin-bottom: 40rpx;
	}

	.auth-modal-logo {
		width: 120rpx;
		height: 120rpx;
		border-radius: 24rpx;
		margin-bottom: 24rpx;
	}

	.auth-modal-title {
		font-size: 40rpx;
		font-weight: 700;
		color: #1F2937;
		margin-bottom: 16rpx;
	}

	.auth-modal-subtitle {
		font-size: 28rpx;
		color: #6B7280;
		line-height: 1.5;
	}

	.auth-modal-content {
		margin-bottom: 40rpx;
	}

	.auth-benefits {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	.benefit-item {
		display: flex;
		align-items: center;
		padding: 16rpx;
		background-color: #F9FAFB;
		border-radius: 16rpx;
	}

	.benefit-icon {
		font-size: 28rpx;
		margin-right: 16rpx;
	}

	.benefit-text {
		font-size: 26rpx;
		color: #374151;
		flex: 1;
	}

	.auth-modal-actions {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	.auth-btn {
		height: 88rpx;
		border-radius: 24rpx;
		font-size: 32rpx;
		font-weight: 600;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.auth-btn-primary {
		background: linear-gradient(135deg, #3B82F6 0%, #1D4ED8 100%);
		color: white;
	}

	.auth-btn-primary:active {
		opacity: 0.9;
	}

	.auth-btn-text {
		background-color: transparent;
		color: #6B7280;
		font-size: 28rpx;
		height: 60rpx;
	}

	.auth-btn-text:active {
		color: #374151;
	}
</style>